<template>
  <GiPageLayout>
    <div class="plugin-list-container main">
      <div class="plugin-list-header">
        <h1>插件管理</h1>
        <div class="plugin-list-actions">
          <a-radio-group v-model="activeTab" type="button">
            <a-radio value="all">官网插件</a-radio>
            <a-radio value="installed">已安装</a-radio>
          </a-radio-group>
          <a-input-search
            v-model="searchKeyword"
            placeholder="搜索插件..."
            style="width: 300px; margin-left: 16px"
            allow-clear
          />
        </div>
      </div>

      <a-divider />

      <div class="plugin-list-filters">
        <a-space>
          <a-select
            v-model="filterType"
            placeholder="插件类型"
            style="width: 160px"
            allow-clear
          >
            <a-option v-for="item of data" :value="item.value" :label="item.label" />
          </a-select>
          <a-select
            v-model="filterCategory"
            :options="availableTags"
            placeholder="插件分类"
            style="width: 160px"
            allow-clear
          >
          </a-select>
          <a-checkbox v-model="showUpdatable">可更新</a-checkbox>
        </a-space>
        <a-button type="text" @click="resetFilters">重置筛选</a-button>
      </div>

      <a-alert
        v-if="fetchFailed && activeTab === 'all'"
        type="warning"
        show-icon
        closable
        style="margin-bottom: 16px"
      >
        查询官网<a href="http://www.gocpu.cn" style="text-decoration: double;color: blue;" target="_blank">gocpu.cn</a>插件失败,请检查网络或者联系官网管理员
      </a-alert>

      <a-spin :loading="loading" tip="加载中...">
        <div v-if="filteredPlugins.length > 0" class="plugin-grid">
          <PluginCard
            v-for="plugin in filteredPlugins"
            :key="plugin.id"
            :plugin="plugin"
            :class="{ 'plugin-disabled': fetchFailed && !plugin.enabled }"
            @install="handlePluginInstall"
            @uninstall="handlePluginUninstall"
            @update="handlePluginUpdate"
          />
        </div>
        <a-empty v-else description="没有找到符合条件的插件" />
      </a-spin>
    </div>
  </GiPageLayout>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import plugin from 'dayjs/plugin/relativeTime'
import PluginCard from './components/PluginCard.vue'
import { pluginApi } from './api/plugin'
import type { PluginDTO } from '@/types/plugins'
import { queryAllPluginsList, queryPluginsList } from '@/apis/system/plugins'

export default defineComponent({
  name: 'PluginList',
  components: {
    PluginCard,
  },
  setup() {
    const plugins = ref<PluginDTO[]>([])
    const loading = ref(true)
    const activeTab = ref('all')
    const searchKeyword = ref('')
    const filterType = ref('')
    const filterCategory = ref('')
    const showUpdatable = ref(false)
    const fetchFailed = ref(false)

    const data = [{
      label: '数据源',
      value: 'datasource',
    }, {
      label: '前端',
      value: 'panel',
    }, {
      label: '应用',
      value: 'app',
    }, {
      label: '系统扩展',
      value: 'ext',
    }]
    const fetchPlugins = async () => {
      try {
        loading.value = true
        if (activeTab.value === 'installed') {
          const { data } = await queryPluginsList()
          plugins.value = data
        } else {
          try {
            // 尝试获取全部插件
            const { data: allPlugins } = await queryAllPluginsList()
            const { data } = await queryPluginsList()

            allPlugins.forEach((plugin) => {
              const installedPlugin = data.find((item) => item.id === plugin.id)
              if (installedPlugin) {
                plugin.enabled = installedPlugin.enabled
                plugin.type = installedPlugin.type
                plugin.hasUpdate = plugin.latestVersion !== installedPlugin.info.version
              }
            })
            plugins.value = allPlugins
            fetchFailed.value = false
          } catch (error) {
            // 获取全部插件失败，仅显示已安装插件
            // const { data } = await queryPluginsList()
            // plugins.value = data
            plugins.value = []
            fetchFailed.value = true
            activeTab.value = 'installed'
            Message.warning('获取官网gocpu.cn插件失败，请检查网络')
          }
        }
      } catch (error) {
        Message.error(`获取插件列表失败: ${error.message}`)
      } finally {
        loading.value = false
      }
    }

    // 获取所有可用的标签
    const availableTags = computed(() => {
      const tags = new Set<string>()
      plugins.value?.forEach((plugin) => {
        plugin.tags?.forEach((tag) => tags.add(tag))
      })
      return Array.from(tags)
    })

    const filteredPlugins = computed(() => {
      // 当在"全部插件"标签页且没有插件数据时，显示空状态
      if (activeTab.value === 'all' && plugins.value.length === 0) {
        return []
      }

      return plugins.value.filter((plugin) => {
        // 搜索关键词过滤
        if (
          searchKeyword.value
          && !plugin.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
          && !plugin.info.description.toLowerCase().includes(searchKeyword.value.toLowerCase())
        ) {
          return false
        }

        // 插件类型过滤
        if (filterType.value && plugin.type !== filterType.value) {
          return false
        }

        // 分类过滤
        if (filterCategory.value && (!plugin.tags || !plugin.tags.includes(filterCategory.value))) {
          return false
        }

        // 可更新过滤
        if (showUpdatable.value && !plugin.hasUpdate) {
          return false
        }
        if (!plugin.info.logos.large.startsWith('http')) {
          if (activeTab.value === 'installed') {
            plugin.info.logos.large = `${import.meta.env.VITE_API_BASE_URL}/logo.svg`
          } else {
            plugin.info.logos.large = `${import.meta.env.VITE_API_BASE_URL}/app/${plugin.id}/${plugin.info.logos.large}`
          }
        }

        return true
      })
    })

    const resetFilters = () => {
      searchKeyword.value = ''
      filterType.value = ''
      filterCategory.value = ''
      showUpdatable.value = false
    }

    const handlePluginInstall = async (id: string) => {
      await fetchPlugins()
    }

    const handlePluginUninstall = async (id: string) => {
      await fetchPlugins()
    }

    const handlePluginUpdate = async (id: string) => {
      // 在实际应用中，这里可能需要刷新特定插件的信息
      await fetchPlugins()
    }

    // 监听标签页变化，重新获取插件列表
    watch(activeTab, () => {
      fetchPlugins()
    })

    onMounted(() => {
      fetchPlugins()
    })

    return {
      data,
      availableTags,
      plugins,
      loading,
      activeTab,
      searchKeyword,
      filterType,
      filterCategory,
      showUpdatable,
      fetchFailed,
      filteredPlugins,
      resetFilters,
      handlePluginInstall,
      handlePluginUninstall,
      handlePluginUpdate,
    }
  },
})
</script>

<style scoped>
::v-deep .gi-page-layout__body {
  overflow-y: auto !important;
}
.plugin-list-container {
  padding: 24px;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
}

.plugin-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.plugin-list-filters {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.plugin-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  width: 100%;
  justify-content: flex-start;
}

.plugin-grid > * {
  flex: 0 0 calc(25% - 15px);
  max-width: calc(25% - 15px);
  min-width: 260px;
}

@media (max-width: 1100px) {
  .plugin-grid > * {
    flex: 0 0 calc(33.333% - 14px);
    max-width: calc(33.333% - 14px);
  }
}

@media (max-width: 900px) {
  .plugin-grid > * {
    flex: 0 0 calc(50% - 10px);
    max-width: calc(50% - 10px);
  }
}

@media (max-width: 768px) {
  .plugin-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .plugin-grid {
    grid-template-columns: 1fr;
  }

  .plugin-list-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .plugin-list-actions {
    margin-top: 16px;
    width: 100%;
  }
}
</style>
